<?php
namespace app\api\controller;

use app\admin\model\goods\GoodsSku;
use app\admin\model\goods\GoodsSkuDetail;
use app\admin\model\order\Spelldetail;
use app\common\controller\Api;
use fast\Utils;
use think\Config;
use think\Db;

/**
 * 任务管理
 */
class Task extends Api
{
    protected $noNeedLogin = ['spellSuccess','joinInfo'];
    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 任务赚信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function index()
    {
        $mobile = $this->auth->mobile;
        $daytime = strtotime(date("Y-m-d",time()));
        $countOrderNum = \app\admin\model\SpellOrder::where('fromUid',$this->auth->id)->where('payStatus',1)->count();
        $dayOrderNum = \app\admin\model\SpellOrder::where('fromUid',$this->auth->id)->where('payStatus',1)->where('payTime','>',$daytime)->count();
        $countPrice = \app\admin\model\rebate\Rebate::where('uid',$this->auth->id)->where('type',6)->sum('price');
        $dayPrice = \app\admin\model\rebate\Rebate::where('uid',$this->auth->id)->where('type',6)->where('createtime','>',$daytime)->sum('price');
/*        $activitytimelimitstatus = \think\config::get("site.activitytimelimitstatus");
        $activitytimelimitsuccess = \think\config::get("site.activitytimelimitsuccess");
        $activitytimelimitbei = \think\config::get("site.activitytimelimitbei");*/
        $data = array(
            "nickname"=>$this->auth->nickname,
            "avatar"=>$this->auth->avatar,
            "mobile"=>!empty($mobile)?substr($mobile, 0,3)."****".substr($mobile, 7,4):"",
            "agent"=>\app\common\model\User::getAgentInfo($this->auth->agent),
            "nums1"=>$countOrderNum,
            "nums2"=>$dayOrderNum,
            "price1"=>$countPrice,
            "price2"=>$dayPrice,
            "percent"=>\think\config::get("site.RobotRebatePercent"),
        /*    "limitstatus"=>intval($activitytimelimitstatus),
            "successnum"=>intval($activitytimelimitsuccess),
            "limitbei"=>intval($activitytimelimitbei),*/
        );
        $this->success("任务赚信息",$data);
    }
    /**
     * 任务赚数据
     * @ApiMethod   (POST)
     * @param string page  分页
     * @param string ptid  拼团号
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function shareOrder()
    {
        $condition = " AND b.orderStatus =2";
        $ptid = $this->request->request("ptid",0);
        if(!empty($ptid)){
            $condition .= " AND a.ptid=".$ptid;
        }
        $keyword = $this->request->request("keyword",0);
        if(!empty($keyword)){
            $condition .= " AND (b.username like '%{$keyword}%' or b.mobile like '%{$keyword}%')";
        }
        $sql = "SELECT a.ptid,a.mobile,a.avatar,b.id,b.goodsName,b.thumb,b.goodsId,b.goodsPrice,b.payPrice FROM `pt_spell` as a join `pt_spell_order` as b on a.ptid=b.id WHERE a.uid!='{$this->auth->id}' AND a.start=1 AND a.isFinished=0 $condition ORDER BY id desc LIMIT " . ($this->page - 1) * $this->limit . "," . $this->limit;
        $list = Db::query($sql);
        foreach ($list as $ks=>&$vs) {
            $goods = \app\admin\model\goods\Goods::where('goodsid', $vs['goodsId'])->field('indexCategory')->find();
            $vs['indexCategory'] = $goods['indexCategory'];
        }
        $data = array(
            "list"=>!empty($list)?$list:[],
        );
        $this->success("全部拼团订单数据",$data);
    }
    /**
     * 拼团成功数据
     * @ApiMethod   (POST)
     * @param string page  分页
     * @param string ptid  拼团号
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function pingOrder()
    {
        $condition = " AND b.orderStatus in(2,3,4,5,6,7,9)";
        $ptid = $this->request->request("ptid",0);
        if(!empty($ptid)){
            $condition .= " AND b.ptid=".$ptid;
        }
        $keyword = $this->request->request("keyword",0);
        if(!empty($keyword)){
            $condition .= " AND (b.username like '%{$keyword}%' or b.mobile like '%{$keyword}%')";
        }
        $sql = "SELECT a.orderId,a.price,a.percent,b.id,b.ptid,b.mobile,b.avatar,b.payPrice,b.goodsId,b.goodsName,b.thumb,b.goodsPrice,b.orderStatus FROM `pt_rebate_list` as a join `pt_spell_order` as b on a.orderId=b.orderId WHERE a.uid='{$this->auth->id}' AND a.type=6 $condition ORDER BY id desc LIMIT ". ($this->page - 1) * $this->limit . "," . $this->limit;
        $list = Db::query($sql);
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $goods = \app\admin\model\goods\Goods::where('goodsid', $vs['goodsId'])->field('indexCategory')->find();
                $vs['indexCategory'] = $goods['indexCategory'];
                $vs['mobile'] = !empty($vs['mobile'])?substr($vs['mobile'], 0,3)."****".substr($vs['mobile'], 7,4):"";
                $spellInfo = \app\admin\model\spell\Spell::where('ptid',$vs['ptid'])->where('start',1)->field('id,mobile,isFinished')->find();
                $vs['spellInfo'] = !empty($spellInfo)?$spellInfo:[];
                $rebateInfo = \app\admin\model\rebate\Rebate::where('orderId',$vs['orderId'])->where('type',6)->where('status',1)->field('id,price')->find();
                $vs['rebateInfo'] = !empty($rebateInfo)?$rebateInfo:[];
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[],
        );
        $this->success("成功拼团订单数据",$data);

        /*$condition = " AND b.orderStatus in(2,3,4,5,6,7,9)";
        $ptid = $this->request->request("ptid",0);
        if(!empty($ptid)){
            $condition .= " AND a.ptid=".$ptid;
        }
        $keyword = $this->request->request("keyword",0);
        if(!empty($keyword)){
            $condition .= " AND (b.username like '%{$keyword}%' or b.mobile like '%{$keyword}%')";
        }
        $sql = "SELECT a.ptid,a.uid,a.mobile,a.avatar,a.price,b.id,b.goodsName,b.thumb,b.goodsPrice,b.payPrice,a.orderId,b.orderStatus FROM `pt_spell` as a join `pt_spell_order` as b on a.orderId=b.orderId WHERE a.start=0 AND a.robot=0 AND a.fromUid='{$this->auth->id}' AND b.fromUid='{$this->auth->id}' $condition ORDER BY id desc LIMIT ". ($this->page - 1) * $this->limit . "," . $this->limit;
        $list = Db::query($sql);
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $spellInfo = \app\admin\model\spell\Spell::where('ptid',$vs['ptid'])->where('start',1)->field('id,mobile,isFinished')->find();
                $vs['spellInfo'] = !empty($spellInfo)?$spellInfo:[];
                $rebateInfo = \app\admin\model\rebate\Rebate::where('orderId',$vs['orderId'])->where('type',6)->where('status',1)->field('id,price')->find();
                $vs['rebateInfo'] = !empty($rebateInfo)?$rebateInfo:[];
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[],
        );
        $this->success("成功拼团订单数据",$data);*/
    }
    /**
     * 分享拼团订单数据
     * @ApiMethod   (POST)
     * @param string ptid  拼团ID
     * @param string goodsId  商品ID
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function shareGoods()
    {
        $ptid = $this->request->request("ptid",0);
        $goodsId = $this->request->request("goodsId",0);
        if(!empty($ptid)){
            $orderInfo = \app\admin\model\SpellOrder::where('id',$ptid)->where('payStatus',1)->where('orderStatus',2)->find();
            $goodsInfo = \app\admin\model\goods\Goods::where('goodsid',$orderInfo['goodsId'])->find();
            if(empty($orderInfo)){
                $this->error("订单信息获取失败");
            }
            $qrcodeUrl = 'http://pt-img.sdgjjy.com/share/pinGroup.html?'."&ptid=".$ptid."&inviteCode=".base64_encode($this->auth->getUser()->invite_code);
            //$qrcodeUrl = Utils::getShortUrl($qrcodeUrl);
            $goodsName = mb_substr($orderInfo['goodsName'],0,36)."...";
            $goodsPrice = $orderInfo['goodsPrice'];
            $oPrice = $goodsInfo['price'];
            if(substr($orderInfo['thumb'],0,2) == '//'){
                $orderInfo['thumb'] = "http:".$orderInfo['thumb'];
            }
            $thumb = $orderInfo['thumb'];
        }elseif(!empty($goodsId)){
            $goodsInfo = \app\admin\model\goods\Goods::where('goodsid',$goodsId)->where('status',1)->find();
            if(empty($goodsInfo)){
                $this->error("商品信息获取失败");
            }
            $qrcodeUrl = 'http://pt-img.sdgjjy.com/share/goodDetail.html?'."&goodsId=".$goodsId."&inviteCode=".base64_encode($this->auth->getUser()->invite_code);
           // $qrcodeUrl = Utils::getShortUrl($qrcodeUrl);
            $goodsName = mb_substr($goodsInfo['title'],0,36)."...";
            $goodsPrice = bcmul($goodsInfo['price'],$goodsInfo['discount']*0.01,2);
            $oPrice = $goodsInfo['price'];
            if(substr($goodsInfo['image'],0,2) == '//'){
                $goodsInfo['image'] = "http:".$goodsInfo['image'];
            }
            $thumb = $goodsInfo['image'];
        }else{
            $this->error("获取失败");
        }
        $data = $this->redis->get($this->cacheKey);
        if(!empty($data)){
            $this->success("商品海报图返回",json_decode($data,true));
        }
        $data = array(
            'orderId'=>isset($orderInfo)?$orderInfo['orderId']:$goodsId,
            "uid"=>$this->auth->id,
            "goodsName"=>$goodsName,
            "price"=>$goodsPrice,
            "oPrice"=>$oPrice,
            "thumb"=>$thumb,
            "qrcode_url"=>$qrcodeUrl,
            "tpl"=>\think\config::get("site.sharegoodsthumb"),
        );
        $poster = new \app\common\library\Goodsposter($data);
        $thumb = $poster->run();

        $data = [
            "inviteCode"=>$this->auth->getUser()->invite_code,
            "thumb"=>$thumb,
            "url"=>$qrcodeUrl
        ];
        $this->redis->set($this->cacheKey,json_encode($data),86400);
        $this->success('商品海报图返回',$data);
    }
    /**
     * 获取更多商品
     * @ApiMethod   (POST)
     * @param string ptid  拼团ID
     * @param string orderId  订单号
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function getMoreGoods()
    {
        $orderId = $this->request->request("orderId","");
        if(!empty($orderId)){
            $orderInfo["orderId"] = $orderId;
        }else {
            $ptid = $this->request->request("ptid", 0);
            if (empty($ptid)) {
                $this->error("订单信息获取失败");
            }
            $orderInfo = \app\admin\model\SpellOrder::where('id', $ptid)->where('payStatus', 1)->where('model', 2)->find();
            if (empty($orderInfo)) {
                $this->error("订单信息获取失败");
            }
        }
        $goodsList = Db::query("SELECT id,goodsId,goodsName,image,skuName,price FROM `pt_spell_detail` WHERE orderId='{$orderInfo['orderId']}' ORDER BY id asc" );
        if(empty($goodsList)){
            $orderInfo['orderId']=substr($orderInfo['orderId'],0,-3);
            $goodsList = Db::query("SELECT id,goodsId,goodsName,image,skuName,price FROM `pt_spell_detail` WHERE orderId='{$orderInfo['orderId']}' ORDER BY id asc" );
        }
        $data = array(
            "list"=>!empty($goodsList)?$goodsList:[]
        );
        $this->success("拼团更多商品",$data);
    }
    /**
     * 邀请拼团人信息
     * @ApiMethod   (POST)
     * @param string day  是否为今天1
     * @param string page 分页
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function inviteOrder()
    {
        $model = new \app\admin\model\SpellOrder();
        $query = $model->where('fromUid',$this->auth->id)->where("payStatus",1);
        $daytime = strtotime(date("Y-m-d",time()));
        $day = $this->request->request("day",0);
        if($day == 1){
            $query->where('payTime','>',$daytime);
        }
        $list = $query->field("id,uid,mobile,goodsId,avatar,orderId,payPrice")
            ->order('id desc')
            ->limit(($this->page-1)*$this->limit,$this->limit)
            ->select();
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $goods = \app\admin\model\goods\Goods::where('goodsid', $vs['goodsId'])->field('indexCategory')->find();
                $vs['indexCategory'] = $goods['indexCategory'];
                $goodsList = Db::query("SELECT id,goodsName,image,skuName,price FROM `pt_spell_detail` WHERE orderId='{$vs['orderId']}' ORDER BY id asc");
                $vs['goodsList'] = !empty($goodsList)?$goodsList:[];
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[],
        );
        $this->success("邀请订单信息",$data);
    }
    /**
     * 团队信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function teamInfo()
    {
        $mobile = $this->auth->mobile;
        $countNum = \app\common\model\Relation::where('pid',$this->auth->id)->count();
        $countOneNum = $this->auth->zhiNum;
        $daytime = strtotime(date("Y-m-d",time()));
        $countPrice = \app\admin\model\rebate\Rebate::where('uid',$this->auth->id)->where('type','in',[6,7,13])->sum('price');
        $dayPrice = \app\admin\model\rebate\Rebate::where('uid',$this->auth->id)->where('type','in',[6,7,13])->where('createtime','>',$daytime)->sum('price');
        $data = array(
            "nickname"=>$this->auth->nickname,
            "avatar"=>$this->auth->avatar,
            "mobile"=>!empty($mobile)?substr($mobile, 0,3)."****".substr($mobile, 7,4):"",
//            "mobile"=>$mobile,
            "agent"=>\app\common\model\User::getAgentInfo($this->auth->agent),
            "nums1"=>$countNum,
            "nums2"=>$countOneNum,
            "price1"=>$countPrice,
            "price2"=>$dayPrice,
        );
        $this->success("团队信息",$data);
    }
    /**
     * 团队会员
     * @ApiMethod   (POST)
     * @param string level  直邀会员1
     * @param string page 分页
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function teamList()
    {
        $condition = "";
        $level = $this->request->request("level",0);
        if(!empty($level)){
            $condition = " AND a.level=".$level;
        }
        $sql = "SELECT a.uid,a.level,b.mobile,b.avatar,b.agent FROM `pt_user_relation` as a join `pt_user` as b on a.uid=b.id WHERE a.pid='{$this->auth->id}' $condition ORDER BY b.id desc LIMIT ". ($this->page - 1) * $this->limit . "," . $this->limit;
        $list = Db::query($sql);
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                if(empty($vs['avatar'])){
                    $vs['avatar'] = letter_avatar($vs['mobile']);
                }
//                $vs['mobile'] = !empty($vs['mobile'])?substr($vs['mobile'], 0,3)."****".substr($vs['mobile'], 7,4):"";
                $vs['mobile'] = $vs['mobile'];
                $vs['countPrice'] = \app\admin\model\rebate\Rebate::where('uid',$this->auth->id)->where('disUid',$vs['uid'])->where('type','in',[6,7,13])->sum('price');
                $vs['agentInfo'] = \app\common\model\User::getAgentInfo($vs['agent']);
                $vs["countNum"] = \app\admin\model\SpellOrder::where('uid',$vs['uid'])->where('model',2)->where('orderStatus','in',[2,3,4,5,6,7,9])->count();
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[]
        );
        $this->success("团队会员数据",$data);
    }
    /**
     * 团队订单详情
     * @ApiMethod   (POST)
     * @param string page 分页
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function teamOrder()
    {
        $sql = "SELECT a.price,a.orderId,a.percent,b.mobile,b.goodsName,b.thumb,b.goodsPrice,b.createtime FROM `pt_rebate_list` as a join `pt_spell_order` as b on a.orderId=b.orderId WHERE a.uid ='{$this->auth->id}' AND a.type in(6,7,13) AND a.status=1 ORDER BY a.id desc LIMIT ". ($this->page - 1) * $this->limit . "," . $this->limit;
        $list = Db::query($sql);
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $vs['mobile'] = !empty($vs['mobile'])?substr($vs['mobile'], 0,3)."****".substr($vs['mobile'], 7,4):"";
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[]
        );
        $this->success("团队订单详情",$data);
    }
    /**
     * 前端请求数据存参团信息
     * @ApiMethod   (POST)
     * @param string inviteCode 邀请码
     * @param string ptid 分页
     * @param string type 类型1邀请2上级
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function userSpell()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $ptid = $this->request->request("ptid",0);
        $type = $this->request->request("type",1);
        if($type == 1){
            $inviteCode = $this->request->request("inviteCode",0);
            if(empty($inviteCode) || empty($ptid)){
                $this->success("信息获取失败");
            }
        }
        Db::startTrans();
        try{
            \app\admin\model\user\Spell::addInfo($this->auth->id,$this->request->request());
        }catch (\Exception $e){
            Db::rollback();
            $this->success("团信息参加失败:".$e->getMessage());
        }
        Db::commit();
        $orderInfo=\app\admin\model\order\Order::where(['id'=>$ptid])->field('orderId,mobile')->find();
        $goodsList=Spelldetail::where(['orderId'=>$orderInfo['orderId']])->field('goodsId,skuId,goodsName,skuName,image,price,quantity')->select();
        foreach ($goodsList as &$row){
            $row['tbPrice']=GoodsSkuDetail::where(['goodsId'=>$row['goodsId'],'skuId'=>$row['skuId']])->value('price');
        }
        $orderInfo['goodsList']=$goodsList;
        $this->success("加入成功",$orderInfo);
    }
    /**
     * 可参团信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function joinInfo()
    {
        $model = new  \app\admin\model\user\Spell();
        $spellInfo = $model->where('uid',$this->auth->id)->where('status',1)->order('id desc')->field('ptid,fromUid')->find();
        $data = array(
            "spellInfo"=>!empty($spellInfo)?[$spellInfo]:[],
            "upList"=>[],
        );
        $nums=0;
        $referee = $this->auth->referee;
        if(empty($spellInfo) && !empty($referee)){
            $upList = \app\admin\model\SpellOrder::where('uid',$referee)->where('model',2)->where('orderStatus',2)->order('id desc')->field('id as ptid,uid as fromUid,avatar,mobile,goodsName,thumb,goodsPrice')->limit('6')->select();
            if(!empty($upList)){
                foreach ($upList as $ks=>$vs){
                    $info = \app\admin\model\spell\Spell::where('uid',$this->auth->id)->where('ptid',$vs['ptid'])->where('robot',0)->find();
                    if(!empty($info)){
                        $vs['isAdd'] =1;
                    }else{
                        $vs['isAdd'] =0;
                        $nums++;
                  }
                }
            }
            $data["upList"] = $nums>1?$upList:[];
        }
        $this->success("可拼团信息",$data);
    }
    /**
     * 展示拼单成功
     * @ApiMethod   (POST)
     * @param string limit 数量
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     */
    public function spellSuccess()
    {
        $model = new \app\admin\model\SpellOrder();
        $list = $model->where('model',2)->where('orderStatus','in',[2,3,4,5,6,7,9])->order('id desc')->field('id,avatar,mobile,goodsName,goodsPrice')->limit($this->limit)->select();
        if(!empty($list)){
            foreach ($list as $ks=>&$vs){
                $vs['mobile'] = substr($vs['mobile'], 0, 3) . "****" . substr($vs['mobile'], 7, 4);
            }
        }
        $data = array(
            "list"=>!empty($list)?$list:[]
        );
        $this->success("拼团成功数据",$data);
    }

    public function shareSpell()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $orderId = $this->request->request("orderId",0);
        $invCode = $this->auth->getUser()->invite_code;
        $orderInfo = \app\admin\model\SpellOrder::where('orderId',$orderId)->where('payStatus',1)->where('orderStatus',2)->find();
        if(empty($orderInfo)) $this->error('该拼团不存');
        $ptinfo = \app\admin\model\spell\Spell::where('orderId',$orderInfo['orderId'])->find();
        $ptinfo['goodsInfo']=(new Spelldetail)->field('id,goodsId,goodsName,image,price')->where(['orderId'=>$ptinfo['orderId']])->select();
        $spellList = (new \app\admin\model\spell\Spell)->where('ptid',$ptinfo['ptid'])->order('id asc')->field('mobile,avatar,price')->select();
        $ptinfo['spellList'] = !empty($spellList)?$spellList:[];
        $ptinfo['regurl']='http://pt-img.sdgjjy.com/share/index.html?inviteCode='.$invCode."&ptid=".$orderInfo['id'];
        $ptid=$orderInfo['id'];
        $qrcodeUrl = $this->auth->getUserUrl()."&ptid=".$ptid;
        $qrcodeUrl = 'http://pt-img.sdgjjy.com/share/pinGroup.html?'."&ptid=".$ptid."&inviteCode=".base64_encode($invCode);
        //$qrcodeUrl = Utils::getShortUrl($qrcodeUrl);
        $goodsName = substr($orderInfo['goodsName'],0,72)."...";
        $goodsPrice = $orderInfo['goodsPrice'];
        if(substr($orderInfo['thumb'],0,2) == '//'){
            $orderInfo['thumb'] = "http:".$orderInfo['thumb'];
        }
        $thumb = $orderInfo['thumb'];
//        $data = $this->redis->get($this->cacheKey);
//        if(!empty($data)){
//            $this->success("商品海报图返回",json_decode($data,true));
//        }
        $data = array(
            'orderId'=>$orderId,
            "uid"=>$this->auth->id,
            "goodsName"=>$goodsName,
            "price"=>$goodsPrice,
            "oPrice"=>bcdiv($goodsPrice,$orderInfo['discount']*0.01,2),
            "thumb"=>$thumb,
            "qrcode_url"=>$qrcodeUrl,
            "tpl"=>\think\config::get("site.sharegoodsthumb"),
        );
        $poster = new \app\common\library\Goodsposter($data);
        $thumb = $poster->run();
        $data = [
            "thumb"=>$thumb,
            "url"=>$qrcodeUrl
        ];
        $ptinfo['thumb']=$thumb;
        $this->success('ok',$ptinfo);
    }
}
